package com.niuwa.p2p.core.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

public class VerifyCodeUtil {

	private int width = 80;
	private int height = 30;
	private String code;

	public VerifyCodeUtil() {
		this(80, 30, getRandomCode(4));
	}

	public VerifyCodeUtil(int width, int height, String code) {
		setWidth(width);
		setHeight(height);
		setCode(code);
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getCode() {
		return code;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getWidth() {
		return width;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public int getHeight() {
		return height;
	}

	public void writeImage(String format, OutputStream out) throws IOException {
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_3BYTE_BGR);
		Graphics2D g = (Graphics2D) image.getGraphics();
		g.setColor(new Color(230, 230, 230));
		g.fillRect(0, 0, width, height);
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);
		Random rand = new Random();
		int num = code.length();

		Font font = g.getFont(); // FONT[rand.nextInt(FONT.length)];
		font = font.deriveFont(Font.PLAIN); // STYLE[rand.nextInt(STYLE.length)]);
		font = font.deriveFont(height * 0.7f);

		int unit = width / num;
		int x = 0;
		int y = height * 8 / 10;

		for (int i = 0; i < num; i++) {
			AffineTransform at = AffineTransform.getRotateInstance(0);
			at.shear(0, 0.1 * rand.nextDouble() - 0.05);
			g.setFont(font.deriveFont(at));

			g.setColor(new Color(rand.nextInt(128), rand.nextInt(128), rand
					.nextInt(128)));
			g.drawString(Character.toString(code.charAt(i)), x, y);
			x += unit;
		}

		// TODO 以下是混淆线条 ，去掉注释后会画出
		for (int i = num << 1; i > 0; i--) {
			g.setColor(new Color(64 + rand.nextInt(192),
					64 + rand.nextInt(192), 64 + rand.nextInt(192)));
			int w = rand.nextInt(width);
			int h = rand.nextInt(height);
			x = rand.nextInt(width - w);
			y = rand.nextInt(height - h);
			g.drawArc(x, y, w, h, 0, rand.nextInt(90));
		}

		ImageIO.write(image, format, out);
	}

	// ======================== static members ================================

	private static Random random;
	static {
		try {
			random = SecureRandom.getInstance("SHA1PRNG");
		} catch (NoSuchAlgorithmException e) {
			random = new Random();
		}
		random.setSeed(System.currentTimeMillis());
	}

	public static String getRandomCode(int length) {
		StringBuilder verifyCode = new StringBuilder();
		for (int i = 0; i < length; i++) {
			int rand = random.nextInt(26);
			int ch = 'A' + rand;
			verifyCode.append((char) ch);
		}
		return verifyCode.toString();
	}

	/**
	 * 生成随机字符串，包括大小写字母、数字
	 * 
	 * @param length
	 * @return
	 */
	public static String getRandomCode2(int length) {
		String result = "";
		String strAll = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_";
		Random rand = new Random();
		for (int i = 0; i < length; i++) {
			int rd = rand.nextInt(63);
			String oneChar = strAll.substring(rd, rd + 1);
			result += oneChar;
		}

		// 判断result是否大小写字母、数字
		Pattern p = Pattern.compile("[A-Z]+");
		Pattern q = Pattern.compile("[a-z]+");
		Pattern r = Pattern.compile("[0-9]+");
		Matcher m = p.matcher(result);
		Matcher n = q.matcher(result);
		Matcher k = r.matcher(result);

		if ((!m.find(0)) || (!n.find(0)) || (!k.find(0))) {
			result = getRandomCode2(6);
		}
		return result;
	}

	public static boolean checkIsValidate(String code) {
		boolean flag = false;
		boolean flag1 = false;
		boolean flag2 = false;
		boolean flag3 = false;
		for (int i = 0; i < code.length(); i++) {
			if (Character.isDigit(code.charAt(i))) {
				flag1 = true;
			}
		}

		if (flag1 && flag2 && flag3) {
			flag = true;
		}
		return flag;
	}

	public static void main(String agrs[]) {
		char[] abc = new char[13];
		abc[0] = 0;
		abc[1] = 1;
		abc[2] = 2;
		abc[3] = 3;
		abc[4] = 4;
		abc[5] = 5;
		abc[6] = 6;
		abc[7] = 7;
		abc[8] = 8;
		abc[9] = 9;
		abc[10] = 'a';
		abc[11] = 'A';
		abc[12] = 'z';
		/*
		 * for(char a:abc){ System.out.println("++++++++++++="+(int)a); }
		 */
		String vcode = getRandomCode2(6);
		System.out.println("++++++++++++++++==========" + vcode);
		System.exit(0);
		// System.out.println(RandomStringUtils.randomAlphanumeric(6));
	}
	
	/**
	 * 生成六位短信数字验证码
	 * 
	 * @param
	 * @return 六位数字验证码
	 */
	public static String getSmsVerificationCode() {
		Random random = new Random();
		String code = "";
		for (int i = 0; i < 6; i++) {
			code += random.nextInt(10);
		}
		return code;
	}
}
